package org.ourgrid.broker.commands.executors;

import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.dao.WorkerDAO;
import org.ourgrid.common.FileTransferInfo;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.worker.controller.actions.GetFilesMessageHandle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;

public class GetFilesExecutor extends SchedulerCommandExecutor {
	
	private String workerID;
	private long requestID;
	private FileTransferInfo[] files;

	/**
	 * <GET_FILES workerID='String' requestID='long'>
	 *    1..n <FILE transferHandleID='long' filePath='String'/> 
	 * </GET_FILES> 
	 */
	public void execute(SchedulerData data, ServiceManager manager) {
		
		fillData(data.getXml());
		
		DeploymentID workerDeploymentID = new DeploymentID(workerID);
		Worker worker = manager.getDAO(WorkerDAO.class).getWorker(workerDeploymentID);
		
		if (worker != null) {
			worker.sendMessage(new GetFilesMessageHandle(requestID, files));
		}	
	}
	
	private void fillData(String xml) {
		
		Document logDocFile = super.getXMl(xml);
		
		Element element = logDocFile.getDocumentElement();
		
		workerID = element.getAttribute("workerID");
		requestID = Long.valueOf(element.getAttribute("requestID"));
		
		int size = element.getElementsByTagName("FILE").getLength();
		files = new FileTransferInfo[size];
		
		FileTransferInfo info = null;
		long transferHandleID = 0;
		String filePath = null;
		
		for (int i = 0; i < size; i++) {
			transferHandleID = Long.valueOf(element.getElementsByTagName("FILE").item(i).getAttributes().
									getNamedItem("transferHandleID").getNodeValue());
			filePath = element.getElementsByTagName("FILE").item(i).getAttributes().
							getNamedItem("filePath").getNodeValue();
			
			info = new FileTransferInfo(transferHandleID, filePath);
			files[i] = info;
		}
	}
	
}
